package com.web.quartz.service.impl;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.web.common.basic.quartz.entity.QuartzJobExecLog;


@Component
public class QuartzJobListener implements JobListener {
	
	private static final String QUARTZ_EXEC_LOG_KEY = "execLog";
	
	public static final String EXEC_SUCCESS_STR = "执行完成";
	
	
	@Autowired
	private QuartzJobExecLogServiceImpl quartzJobExecLogServiceImpl;

	@Override
	public String getName() {
		return "jobListener-log";
	}

	@Override
	public void jobToBeExecuted(JobExecutionContext context) {
		//定时任务开始执行
		JobDetail jobDetail = context.getJobDetail();
		if(jobDetail == null) {
			return;
		}
		QuartzJobExecLog log = new QuartzJobExecLog();
		log.setJobName(jobDetail.getKey().getName());
		log.setJobGroup(jobDetail.getKey().getGroup());
		log.setDescription(jobDetail.getDescription());
		log.setJobClassName(jobDetail.getJobClass().getName());
		log.setTriggerType(context.getTrigger().getClass().getSimpleName());
		log.setExecStartTime(LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
		context.put(QUARTZ_EXEC_LOG_KEY, log);
	}

	@Override
	public void jobExecutionVetoed(JobExecutionContext context) {
		Object data = context.get(QUARTZ_EXEC_LOG_KEY);
		if(!(data instanceof QuartzJobExecLog)) {
			return;
		}
		QuartzJobExecLog log = (QuartzJobExecLog) data;
		log.setExecEndTime(LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
		log.setExecResult("定时任务被禁止");
		quartzJobExecLogServiceImpl.saveExecLog(log);
	}

	@Override
	public void jobWasExecuted(JobExecutionContext context, JobExecutionException jobException) {
		Object data = context.get(QUARTZ_EXEC_LOG_KEY);
		if(!(data instanceof QuartzJobExecLog)) {
			return;
		}
		QuartzJobExecLog log = (QuartzJobExecLog) data;
		log.setExecEndTime(LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
		if(jobException != null) {
			log.setExecResult(jobException.getMessage());
		}else {
			log.setExecResult(EXEC_SUCCESS_STR);
		}
		quartzJobExecLogServiceImpl.saveExecLog(log);
	}

}
